package com.qf.shopping.dao.impl;

import com.qf.shopping.dao.IUserDao;
import com.qf.shopping.entity.User;
import com.qf.shopping.utils.Tools;

import java.util.List;

/**用户模块与数据库的交互
 * @author 三旬
 * @version 1.0  2022/9/13
 */

public class UserDapImpl implements IUserDao {

    @Override
    public Integer insert(User user) {
        String sql = "insert into t_user (username,password,age,sex,email,statu,create_time) values(?,?,?,?,?,0,now()) ";
        return Tools.update(sql,user.getUserName(),user.getPassWord(),user.getAge(),user.getSex(),user.getEmail());
    }

    @Override
    public Integer deleteById(Integer id) {
        String sql = "delete from t_user where id = ?";
        return Tools.update(sql,id);
    }

    @Override
    public Integer updateById(User user) {
        String sql = "update t_user set username = ?,age = ?, sex = ?,email = ? where id = ?";
        return Tools.update(sql,user.getUserName(),user.getAge(),user.getSex(),user.getEmail(),user.getId());
    }

    @Override
    public User selectOneById(Integer id) {
        String sql = "select * from t_user where id = ?";
        return Tools.selectOne(sql,User.class,id);
    }

    @Override
    public List<User> selectAll() {
        String sql = "select * from t_user";
        return Tools.selectList(sql,User.class);
    }

    @Override
    public List<User> selectPage(Integer index, Integer size) {
        String sql = "select * from t_user limit ?,?";
        return Tools.selectList(sql,User.class,index,size);
    }

    @Override
    public Integer counts() {
        String sql = "select * from t_user";
        List<User> list  =Tools.selectList(sql,User.class);
        if(list != null){
            return list.size();
        }
        return 0;
    }

    @Override
    public Integer delChecked(List<Integer> list) {
        StringBuilder sql = new StringBuilder("delete from t_user where id in(");
        for (int i = 0; i < list.size(); i++) {
            if(i < list.size() - 1){
                sql.append("?,");
            }else{
                sql.append("?");
            }
        }
        sql.append(")");
        return Tools.update(sql.toString(),list.toArray());
    }

    @Override
    public User selectByName(String userName) {
        String sql = "select * from t_user where username = ?";
        return Tools.selectOne(sql,User.class,userName);
    }

    @Override
    public User selectByCode(String keyCode) {
        String sql = "select * from t_user where keyCode = ?";
        return Tools.selectOne(sql,User.class,keyCode);
    }

    @Override
    public Integer updateUserStatu(Integer id, int statu) {
        String sql = "update t_user set statu = ? where id = ?";
        return Tools.update(sql,statu,id);
    }
}
